import sys

sys.path.append("/data/lhj/Agent/OpenManus_hamster")
import asyncio
import time

from app.agent import ExcelCleanAgent
from app.agent.game_data_analysis import GameDataAnalysisAgent
from app.agent.lead_agent import MultiDataAnalysisCoordinator
from app.agent.manus import Manus
from app.flow.data_analysis_flow import data_analysis_flow
from app.flow.flow_factory import FlowFactory, FlowType
from app.logger import logger
from app.tool.excel_analysis import (
    ControlTestAnalysisTool,
    ExcelCleanTool,
    ExcelColumnAnalysisTool,
    ExcelJsonMetadataReadTool,
    ExcelSplitMultipleSubtableTool,
    ExcelSplitSubtableTool,
)
from app.tool.merge_multi_md_into_one_tool import MergeMultiMdIntoOneTool
from app.tool.python_execute import PythonExecute
from app.tool.spawn_multi_data_analysis_tool import SpawnMultiDataAnalysisTool
from app.tool.excel_analysis.excel_split_to_key_metric_tool import ExcelSplitToKeyMetricTool
from app.tool.excel_analysis.key_metric_analysis import KeyMetricAnalysisTool

async def test_excel_clean_tool():
    tool = ExcelCleanTool()

    # Basic usage
    result = await tool.execute(
        file_path="/data/lhj/Agent/OpenManus_hamster/workspace/total_data.csv"
    )
    print("Basic Usage Result:", result)


async def test_excel_column_analysis_tool():
    tool = ExcelColumnAnalysisTool()

    # Basic usage
    result = await tool.execute(
        file_path="/data/lhj/Agent/OpenManus_hamster/workspace/csv_file/yahngyang_moonton_com_20250529170533-8067108_cleaned.csv"
    )
    print(result)


async def test_excel_split_subtable_tool():
    tool = ExcelSplitSubtableTool()

    # Basic usage
    result = await tool.execute(
        csv_file_path="/data/lhj/Agent/OpenManus_hamster/workspace/csv_file/yahngyang_moonton_com_20250529170533-8067108_cleaned.csv",
        json_metadata_path="/data/lhj/Agent/OpenManus_hamster/workspace/csv_file/yahngyang_moonton_com_20250529170533-8067108_cleaned_column_analysis.json",
        common_columns=["param_value", "unityversion_inner"],
    )
    print(result)


async def test_excel_json_metadata_read_tool():
    tool = ExcelJsonMetadataReadTool()

    # Basic usage
    result = await tool.execute(
        json_metadata_path="/data/lhj/Agent/OpenManus_hamster/workspace/csv_file/yahngyang_moonton_com_20250529170533-8067108_cleaned_column_analysis.json",
        column_names=["param_value", "unityversion_inner"],
        include_reasoning=True,
    )
    print(result.output)


async def test_ExcelCleanAgent():
    agent = await ExcelCleanAgent.create()

    prompt = """
    请分析位于 /data/lhj/Agent/OpenManus_hamster/workspace/csv_file2/yahngyang_moonton_com_20250529170533-8067108.csv 的CSV文件。
    该文件包含从运行两个版本游戏引擎的多个设备收集的性能指标（例如，FPS、内存使用量、CPU使用率）：
    对照组（param_value列）：旧引擎版本
    测试组（param_value列）：新引擎版本
    """
    result = await agent.run(prompt)
    print(result)


async def test_SpawnMultiDataAnalysisTool():
    tool = SpawnMultiDataAnalysisTool()

    # Basic usage
    result = await tool.execute(
        directory_path="/mnt/e/lhj/OpenManus_hamster/workspace/split_results",
        max_concurrent_agents=4,
    )
    print(result.output)


async def test_merge_multi_md_into_one_tool():
    tool = MergeMultiMdIntoOneTool()

    # Basic usage
    result = await tool.execute(
        directory_path="/mnt/e/lhj/OpenManus_hamster/workspace/split_tables",
        output_file_path="/data/lhj/Agent/OpenManus_hamster/workspace/output/merged_docs.md",
        add_headers=False,
    )
    print(result.output)


async def test_data_analysis_flow():
    agents = {
        "ExcelCleanAgent": ExcelCleanAgent(),
        "MultiDataAnalysisCoordinator": MultiDataAnalysisCoordinator(),
    }

    flow  = FlowFactory.create_flow(
        flow_type = FlowType.GAME_DATA_ANALYSIS,
        agents = agents,
        data_file_path = "/data/lhj/Agent/OpenManus_hamster/workspace/total_data.csv"
    )

    prompt = """
    请分析位于 /data/lhj/Agent/OpenManus_hamster/workspace/total_data.csv 的CSV文件。
    该文件包含从运行两个版本游戏引擎的多个设备收集的性能指标（例如，FPS、内存使用量、CPU使用率）：
    对照组（param_value列）：旧引擎版本
    测试组（param_value列）：新引擎版本"""

    try:
        start_time = time.time()
        result = await asyncio.wait_for(
            flow.execute(prompt),
            timeout=7200,
        )
        elapsed_time = time.time() - start_time
        logger.info(f"Request processed in {elapsed_time:.2f} seconds")
        logger.info(result)
    except asyncio.TimeoutError:
        logger.error("Request processing timed out after 1 hour")
        logger.info(
            "Operation terminated due to timeout. Please try a simpler request."
        )


async def test_python_execute():
    # 初始化工具
    tool = PythonExecute()

    # # 方法1：通过 conda 环境名
    # result = await tool.execute(
    #     code="import seaborn; print(seaborn.__version__)",
    #     conda_env="manus"
    # )

    # 方法2：通过 Python 路径
    result = await tool.execute(code="import seaborn; print(seaborn.__version__)")
    print("Python Execute Result:", result)


async def test_excel_split_multiple_subtable_tool():
    tool = ExcelSplitMultipleSubtableTool()

    # Basic usage
    result = await tool.execute(
        csv_file_path="/data/lhj/Agent/OpenManus_hamster/workspace/total_data_cleaned.csv",
        common_columns=["param_value", "devicemodel"],
    )
    print(result)


async def test_control_test_analysis_tool():
    tool = ControlTestAnalysisTool()

    # Basic usage
    result = await tool.execute(
        csv_file_path="/data/lhj/Agent/OpenManus_hamster/workspace/splitsubtable_multiple/fps_subtables/fps_1_subtable.csv",
        group_column="param_value",  # 默认值，可省略
        control_value="control",  # 默认值，可省略
        test_value="test",  # 默认值，可省略
        degradation_threshold=1.0,  # 恶化阈值1%
        output_dir="/data/lhj/Agent/OpenManus_hamster/workspace/test",
    )
    print(result)
    
async def test_key_metric():
    tool = ExcelSplitToKeyMetricTool()

    # Basic usage
    result = await tool.execute(
        csv_file_path="/data/lhj/Agent/OpenManus_hamster/workspace2/total_data_cleaned.csv")
    print(result)
    
    # key_analysis_tool = KeyMetricAnalysisTool()
    # result = await key_analysis_tool.execute()

async def test_key_metric_analysis_tool():
    tool = KeyMetricAnalysisTool()

    # Basic usage
    result = await tool.execute(
        csv_file_path="/data/lhj/Agent/OpenManus_hamster/workspace2/key_metric.csv"
    )
    print(result)


if __name__ == "__main__":
    # asyncio.run(test_excel_clean_tool())
    # asyncio.run(test_excel_column_analysis_tool())
    # asyncio.run(test_excel_split_subtable_tool())
    # asyncio.run(test_excel_json_metadata_read_tool())
    # asyncio.run(test_ExcelCleanAgent())
    # asyncio.run(test_SpawnMultiDataAnalysisTool())
    # asyncio.run(test_merge_multi_md_into_one_tool())
    # asyncio.run(test_data_analysis_flow())
    # asyncio.run(test_python_execute())
    # asyncio.run(test_excel_split_multiple_subtable_tool())
    # asyncio.run(test_control_test_analysis_tool())
    # asyncio.run(test_key_metric())
    asyncio.run(test_key_metric_analysis_tool())
